import Picture
import json
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.iai.v20200303 import iai_client, models
from PIL import Image

def get_all():
    try:
        cred = credential.Credential("AKIDud9M3U3vKWTO30sUdZK5buyrVzGMqiV2", "QsGSRDmAQoNipiZBdohKhncNs66oGRM2")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "iai.tencentcloudapi.com"
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = iai_client.IaiClient(cred, "ap-shanghai", clientProfile)
        req = models.GetPersonListRequest()
        params = {
            "GroupId": "DLUT"
        }
        req.from_json_string(json.dumps(params))
        resp = client.GetPersonList(req)
        ans = json.loads(resp.to_json_string())
        return ans["PersonInfos"]
    except TencentCloudSDKException as err:
        print(err)

def add():
    pic = Picture.photo()
    Url = Picture.pic_to_url(pic)
    name = input("请输入您的名字：")
    judge = True
    while judge:
        ID = input("请输入您的学号：")
        judge=False
        for i in range(0,len(ID)):
            if(ID[i]<"0" or ID[i]>"9"):
                judge=True
                break
        if judge:
            print("输入学号不符合要求！")
    Gender = input("请输入你的性别：\n1、男性\n2、女性\n")
    judge = True
    all_data = get_all()
    for i in range(0,len(all_data)):
        if(all_data[i]["PersonId"]==ID):
            judge=False
            break
    if(judge):
        #没有这个人
        try:
            cred = credential.Credential("AKIDud9M3U3vKWTO30sUdZK5buyrVzGMqiV2", "QsGSRDmAQoNipiZBdohKhncNs66oGRM2")
            httpProfile = HttpProfile()
            httpProfile.endpoint = "iai.tencentcloudapi.com"
            clientProfile = ClientProfile()
            clientProfile.httpProfile = httpProfile
            client = iai_client.IaiClient(cred, "ap-shanghai", clientProfile)
            req = models.CreatePersonRequest()
            params = {
                "GroupId": "DLUT",
                "PersonName": name,
                "PersonId": ID,
                "Gender": int(Gender),
                "Url": Url,
                "UniquePersonControl": 2,
                "QualityControl": 0,
                "NeedRotateDetection": 1
            }
            req.from_json_string(json.dumps(params))
            resp = client.CreatePerson(req)
            ans = json.loads(resp.to_json_string())
            return ans
        except TencentCloudSDKException as err:
            print(err)
    else:
        try:
            cred = credential.Credential("AKIDud9M3U3vKWTO30sUdZK5buyrVzGMqiV2", "QsGSRDmAQoNipiZBdohKhncNs66oGRM2")
            httpProfile = HttpProfile()
            httpProfile.endpoint = "iai.tencentcloudapi.com"

            clientProfile = ClientProfile()
            clientProfile.httpProfile = httpProfile
            client = iai_client.IaiClient(cred, "ap-shanghai", clientProfile)

            req = models.CreateFaceRequest()
            params = {
                "PersonId": ID,
                "Urls": [Url],
                "QualityControl": 0,
                "NeedRotateDetection": 1
            }
            req.from_json_string(json.dumps(params))
            resp = client.CreateFace(req)
            ans = json.loads(resp.to_json_string())
            return ans
        except TencentCloudSDKException as err:
            print(err)

def search():
    pic = Picture.photo()
    Url = Picture.pic_to_url(pic)
    answer  =[]

    try:
        cred = credential.Credential("AKIDud9M3U3vKWTO30sUdZK5buyrVzGMqiV2", "QsGSRDmAQoNipiZBdohKhncNs66oGRM2")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "iai.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = iai_client.IaiClient(cred, "ap-shanghai", clientProfile)

        req = models.DetectFaceRequest()
        params = {
            "MaxFaceNum": 1,
            "Url": Url,
            "NeedFaceAttributes": 1,
            "NeedQualityDetection": 1,
            "NeedRotateDetection": 1
        }
        req.from_json_string(json.dumps(params))
        resp = client.DetectFace(req)
        ans = json.loads(resp.to_json_string())
        answer.append(ans)
    except TencentCloudSDKException as err:
        print(err)

    try:
        cred = credential.Credential("AKIDud9M3U3vKWTO30sUdZK5buyrVzGMqiV2", "QsGSRDmAQoNipiZBdohKhncNs66oGRM2")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "iai.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = iai_client.IaiClient(cred, "ap-shanghai", clientProfile)

        req = models.SearchFacesRequest()
        params = {
            "GroupIds": ["DLUT"],
            "Url": Url,
            "MaxFaceNum": 1,
            "MaxPersonNum": 3,
            "NeedPersonInfo": 1,
            "QualityControl": 0,
            "NeedRotateDetection": 1
        }
        req.from_json_string(json.dumps(params))
        resp = client.SearchFaces(req)
        ans = json.loads(resp.to_json_string())
        answer.append(ans)
    except TencentCloudSDKException as err:
        print(err)
    return answer

def search_1():
    img = Image.open("./Pic/1.jpg")  # 返回一个Image对象
    img.show()
    Url = "http://pic.cpolar.cn/1.jpg"
    answer  =[]

    try:
        cred = credential.Credential("AKIDud9M3U3vKWTO30sUdZK5buyrVzGMqiV2", "QsGSRDmAQoNipiZBdohKhncNs66oGRM2")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "iai.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = iai_client.IaiClient(cred, "ap-shanghai", clientProfile)

        req = models.DetectFaceRequest()
        params = {
            "MaxFaceNum": 1,
            "Url": Url,
            "NeedFaceAttributes": 1,
            "NeedQualityDetection": 1,
            "NeedRotateDetection": 1
        }
        req.from_json_string(json.dumps(params))
        resp = client.DetectFace(req)
        ans = json.loads(resp.to_json_string())
        answer.append(ans)
    except TencentCloudSDKException as err:
        print(err)

    try:
        cred = credential.Credential("AKIDud9M3U3vKWTO30sUdZK5buyrVzGMqiV2", "QsGSRDmAQoNipiZBdohKhncNs66oGRM2")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "iai.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = iai_client.IaiClient(cred, "ap-shanghai", clientProfile)

        req = models.SearchFacesRequest()
        params = {
            "GroupIds": ["DLUT"],
            "Url": Url,
            "MaxFaceNum": 1,
            "MaxPersonNum": 3,
            "NeedPersonInfo": 1,
            "QualityControl": 0,
            "NeedRotateDetection": 1
        }
        req.from_json_string(json.dumps(params))
        resp = client.SearchFaces(req)
        ans = json.loads(resp.to_json_string())
        answer.append(ans)
    except TencentCloudSDKException as err:
        print(err)
    return answer

def search_2():
    img = Image.open("./Pic/2.jpg")  # 返回一个Image对象
    img.show()
    Url = "http://pic.cpolar.cn/2.jpg"
    answer  =[]

    try:
        cred = credential.Credential("AKIDud9M3U3vKWTO30sUdZK5buyrVzGMqiV2", "QsGSRDmAQoNipiZBdohKhncNs66oGRM2")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "iai.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = iai_client.IaiClient(cred, "ap-shanghai", clientProfile)

        req = models.DetectFaceRequest()
        params = {
            "MaxFaceNum": 1,
            "Url": Url,
            "NeedFaceAttributes": 1,
            "NeedQualityDetection": 1,
            "NeedRotateDetection": 1
        }
        req.from_json_string(json.dumps(params))
        resp = client.DetectFace(req)
        ans = json.loads(resp.to_json_string())
        answer.append(ans)
    except TencentCloudSDKException as err:
        print(err)

    try:
        cred = credential.Credential("AKIDud9M3U3vKWTO30sUdZK5buyrVzGMqiV2", "QsGSRDmAQoNipiZBdohKhncNs66oGRM2")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "iai.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = iai_client.IaiClient(cred, "ap-shanghai", clientProfile)

        req = models.SearchFacesRequest()
        params = {
            "GroupIds": ["DLUT"],
            "Url": Url,
            "MaxFaceNum": 1,
            "MaxPersonNum": 3,
            "NeedPersonInfo": 1,
            "QualityControl": 0,
            "NeedRotateDetection": 1
        }
        req.from_json_string(json.dumps(params))
        resp = client.SearchFaces(req)
        ans = json.loads(resp.to_json_string())
        answer.append(ans)
    except TencentCloudSDKException as err:
        print(err)
    return answer

if __name__ == '__main__':
    while(True):
        flag = int(input("请输入需要进行的模块：\n1、增加人脸库\n2、人脸搜索\n3、其他人脸（有口罩）\n4、其他人脸（无口罩）\n5、退出\n"))
        if flag==1:
            data = add()
            #print(data)
            print("添加人脸成功")
        elif flag==2:
            data = search()
            print("口罩佩戴情况：",end="\t")
            if data[0]["FaceInfos"][0]["FaceAttributesInfo"]["Mask"]:
                print("佩戴口罩")
            else:
                print("未佩戴口罩")
            print("口罩佩戴标准：", end="\t")
            if data[0]["FaceInfos"][0]["FaceQualityInfo"]["Completeness"]["Nose"]<=40 and data[0]["FaceInfos"][0]["FaceQualityInfo"]["Completeness"]["Mouth"]<=40:
                print("口罩佩戴标准")
            else:
                print("未有效佩戴")
            print("学号为：",end="\t")
            print(data[1]["Results"][0]["Candidates"][0]["PersonId"])
            print("姓名为：",end="\t")
            print(data[1]["Results"][0]["Candidates"][0]["PersonName"])
        elif flag==3:
            data = search_1()
            print("口罩佩戴情况：",end="\t")
            if data[0]["FaceInfos"][0]["FaceAttributesInfo"]["Mask"]:
                print("佩戴口罩")
            else:
                print("未佩戴口罩")
            print("口罩佩戴标准：", end="\t")
            if data[0]["FaceInfos"][0]["FaceQualityInfo"]["Completeness"]["Nose"]<=40 and data[0]["FaceInfos"][0]["FaceQualityInfo"]["Completeness"]["Mouth"]<=40:
                print("口罩佩戴标准")
            else:
                print("未有效佩戴")
            print("学号为：",end="\t")
            print(data[1]["Results"][0]["Candidates"][0]["PersonId"])
            print("姓名为：",end="\t")
            print(data[1]["Results"][0]["Candidates"][0]["PersonName"])
        elif flag==4:
            data = search_2()
            print("口罩佩戴情况：",end="\t")
            if data[0]["FaceInfos"][0]["FaceAttributesInfo"]["Mask"]:
                print("佩戴口罩")
            else:
                print("未佩戴口罩")
            print("口罩佩戴标准：", end="\t")
            if data[0]["FaceInfos"][0]["FaceQualityInfo"]["Completeness"]["Nose"]<=40 and data[0]["FaceInfos"][0]["FaceQualityInfo"]["Completeness"]["Mouth"]<=40:
                print("口罩佩戴标准")
            else:
                print("未有效佩戴")
            print("学号为：",end="\t")
            print(data[1]["Results"][0]["Candidates"][0]["PersonId"])
            print("姓名为：",end="\t")
            print(data[1]["Results"][0]["Candidates"][0]["PersonName"])
        else:
            break